
package com.xxl.job.admin.core.alarm.impl;

import cn.hutool.core.net.NetUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.model.ReturnT;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.MessageFormat;

/**
 * job alarm by email
 *
 * @author xuxueli 2020-01-19
 */
@Component
public class FeishuJobAlarm implements JobAlarm {
    private static Logger logger = LoggerFactory.getLogger(FeishuJobAlarm.class);

    /**
     * fail alarm
     *
     * @param jobLog
     */
    @Override
    public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
        boolean alarmResult = true;
        if (!XxlJobAdminConfig.getAdminConfig().isSendFeishu()) {
            return alarmResult;
        }

        // send monitor email
        if (info != null && info.getAuthor() != null && info.getAuthor().trim().length() > 0) {

            // alarmContent
            String alarmContent = "Alarm Job LogId=" + jobLog.getId();
            if (jobLog.getTriggerCode() != ReturnT.SUCCESS_CODE) {
                alarmContent += "<br>TriggerMsg=<br>" + jobLog.getTriggerMsg();
            }
            if (jobLog.getHandleCode() > 0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) {
                alarmContent += "<br>HandleCode=" + jobLog.getHandleMsg();
            }

            // email info
            XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(Integer.valueOf(info.getJobGroup()));
            String personal = I18nUtil.getString("admin_name_full");
            String title = I18nUtil.getString("jobconf_monitor");
            String content = MessageFormat.format(loadEmailJobAlarmTemplate(),
                    group != null ? group.getTitle() : "null",
                    info.getId(),
                    info.getJobDesc(),
                    alarmContent);
            try {
                for (String s : info.getAuthor().split(",")) {
                    // 发送飞书消息
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("title", title);
                    jsonObject.put("user", s);
                    jsonObject.put("message", content);
                    int port = Solon.cfg().getInt("server.port", 0);
                    String hostAddress = NetUtil.getLocalhost().getHostAddress() + ":" + port;
                    jsonObject.put("ip", hostAddress);
                    String body = HttpRequest.post(XxlJobAdminConfig.getAdminConfig().getFeishuUrl())
                            .body(jsonObject.toJSONString()).timeout(5000)
                            .execute().body();
                    logger.debug("发送飞书消息结果：{}", body);
                }
            } catch (Exception e) {
                logger.error(">>>>>>>>>>> xxl-job, job fail alarm email send error, JobLogId:{}", jobLog.getId(), e);
                alarmResult = false;
            }
        }

        return alarmResult;
    }

    /**
     * load email job alarm template
     *
     * @return
     */
    private static final String loadEmailJobAlarmTemplate() {
        // 改成飞书消息模板,不加html标签
        String mailBodyTemplate = I18nUtil.getString("jobconf_monitor_detail") + "：\n" +
                                  "      " + I18nUtil.getString("jobinfo_field_jobgroup") + ": {0}\n" +
                                  "      " + I18nUtil.getString("jobinfo_field_id") + ": {1}\n" +
                                  "      " + I18nUtil.getString("jobinfo_field_jobdesc") + ": {2}\n" +
                                  "      " + I18nUtil.getString("jobconf_monitor_alarm_content") + ": \n" +
                                  "      {3}\n";
        return mailBodyTemplate;
    }

}
